package com.stedu.mall.common.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.config.WhiteLIstConfig;
import com.stedu.mall.common.utils.JwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class jwtInterceptor implements HandlerInterceptor {
    @Autowired
    private WhiteLIstConfig whiteLIstConfig;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求是否在白名单中 - 方行
        String path=request.getRequestURI();
        String method= request.getMethod();

        if (whiteLIstConfig.getRules()!=null && whiteLIstConfig.getRules()
                .stream()
                .anyMatch(rule -> rule.getMethod().equalsIgnoreCase(method) && path.matches(rule.getRegPath()))) {
            return  true;
        }
        /*
        * 判断浏览器发送过来的jwt是否正确
        * 1.正确放行
        * 2.错误拦截
        * */
        //对OPTIONS请求放行，不然会出现跨域问题
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            return true;
        }
        //获取token
        String token = request.getHeader("token");
        RespBean respBean = null;
        try {
            //解析JWT，如果出现问题会抛出异常
            Map<String, Object> map = JwtUtil.parseJwtToMap(token);
            //生成新的jwt
            String jwt = JwtUtil.generateJwt(map);
            response.setHeader("token",jwt);
            response.setHeader("Access-Control-Expose-Headers","token");
            return true;
        } catch (SignatureVerificationException e) {
            respBean = RespBean.error("无效签名");
        } catch (TokenExpiredException e) {
            respBean = RespBean.error("令牌超时");
        } catch (AlgorithmMismatchException e) {
            respBean = RespBean.error("算法不匹配");
        } catch (Exception e) {
            respBean = RespBean.error("令牌无效");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json;charset=utf-8");
        objectMapper.writeValue(response.getOutputStream(), respBean);
        return false;

    }


}
